package com.lanou.musicproject.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;
import com.lanou.musicproject.R;
import com.lanou.musicproject.activity.MoreSongActivity;
import com.lanou.musicproject.activity.MoreSongInfoActivity;
import com.lanou.musicproject.activity.RotateInfoActivity;
import com.lanou.musicproject.adapter.RecommHotSongAdapter;
import com.lanou.musicproject.adapter.RecommNewSongAdapter;
import com.lanou.musicproject.adapter.RecommPagerAdapter;
import com.lanou.musicproject.adapter.RecommSongListAdapter;
import com.lanou.musicproject.bean.NewSong;
import com.lanou.musicproject.bean.RecommHotSong;
import com.lanou.musicproject.bean.Rotate;
import com.lanou.musicproject.bean.SongListRecomm;
import com.lanou.musicproject.net.HttpHelper;
import com.lanou.musicproject.net.NetDataCallBack;
import com.lanou.musicproject.net.NetDataWhat;
import com.lanou.musicproject.tools.NoScrollGridView;
import com.lanou.musicproject.tools.NoScrollListView;
import com.lanou.musicproject.volley.VolleySingleton;

import java.util.List;

import butterknife.ButterKnife;

import static android.view.ViewGroup.LayoutParams;

/**
 * Created by 王世美 on 15/10/23.
 * 推荐页
 */
public class RecommFragment extends Fragment implements
        ViewPager.OnPageChangeListener, NetDataCallBack, NetDataWhat {
    private TextView allTv;
    private  NoScrollGridView songListGV,newSongGV;
    private NoScrollListView hotSongLV;

    private ViewPager viewPager;
    private LinearLayout viewPicture;
    // 最新歌曲 更多按钮
    private TextView moreSongTV;

    // 网络拉取工具类
    private HttpHelper httpHelper;

    // 定义轮播图适配器
    private RecommPagerAdapter adapter;
    // 定义歌单推荐页适配器
    private RecommSongListAdapter songListAdapter;
    // 定义热门歌曲推荐适配器
    private RecommHotSongAdapter hotSongAdapter;
    // 定义最新歌曲适配器
    private RecommNewSongAdapter newSongAdapter;
    // 定义轮播图实体类数组
    private List<Rotate.PicEntity> urls;
    private List<Rotate.PicEntity> picEntity;
    // 定义歌单推荐实体类数组
    private List<SongListRecomm.ContentEntity.ListEntity> songList;
    // 定义热门歌曲推荐实体类数组
    private List<RecommHotSong.ContentEntity.SongListEntity> hotSong;
    // 定义最新歌曲实体类数组
    private List<NewSong.PlazeAlbumListEntity.RMEntity.AlbumListEntity.ListEntity> newSong;
    // 定义一个线性布局
    private LinearLayout linearLayout;
    //开启线程
    private Handler startHandler;
    //发送消息
    private Handler msgHandler;
    private HandlerThread handlerThread;
    //存储状态
    private boolean isFlag = false;
    private VolleySingleton volleySingleton;
    private ImageLoader imageLoader;
    // 轮播间隔时间
    private static final int TIME = 3000;
    private int currentPage;
    private boolean isNetDone = false;
    private IntentListener myListener;
    private  TextView songlist_more;




    //mainactivity相应接口i跳转
    public interface IntentListener{
        void onListener(String str);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        myListener = (IntentListener) context;
    }

    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        // 加载布局

        View v = inflater.inflate(R.layout.fragment_recomm, null);
        ButterKnife.bind(getActivity());

        allTv = (TextView) v.findViewById(R.id.allTv);
        allTv.setText(R.string.recomm_songlist);
        //更多
        songlist_more = (TextView) v.findViewById(R.id.songlist_more);
        songlist_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getId() == R.id.songlist_more) {
                    myListener.onListener("songlist");

                }

            }
        });
        // 更多按钮
        moreSongTV = (TextView) v.findViewById(R.id.moreSongTV);
        moreSongTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(),
                        MoreSongActivity.class);
                startActivity(intent);
            }
        });
        songListGV = (NoScrollGridView) v.findViewById(R.id.songListGV);
        songListGV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SongListRecomm.ContentEntity.ListEntity entity = (SongListRecomm.ContentEntity.ListEntity
                        ) parent.getItemAtPosition(position);
                Intent intent = new Intent(getActivity(), RotateInfoActivity.class);
                intent.putExtra("listid", entity.getListid());
                startActivity(intent);
            }
        });
        hotSongLV = (NoScrollListView) v.findViewById(R.id.hotSongLV);
        newSongGV = (NoScrollGridView) v.findViewById(R.id.newSongGV);
        newSongGV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NewSong.PlazeAlbumListEntity.RMEntity.AlbumListEntity.ListEntity entity =
                        (NewSong.PlazeAlbumListEntity.RMEntity.AlbumListEntity.ListEntity)
                                parent.getItemAtPosition(position);
                Intent intent = new Intent(getActivity(), MoreSongInfoActivity.class);
                intent.putExtra("album_id", entity.getAlbum_id());
                startActivity(intent);
            }
        });
        volleySingleton = VolleySingleton.getInstance(getActivity());
        return v;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewPager = (ViewPager) getActivity().findViewById(R.id.viewPager);
        viewPicture = (LinearLayout) getActivity().findViewById(R.id.viewPicture);
        httpHelper = new HttpHelper(this);
        httpHelper.getRotatePage();
        httpHelper.getSongListPage();
        httpHelper.getHotSongPage();
        httpHelper.getNewSongPage();
        imageLoader = volleySingleton.getImageLoader();
        startHandler = new Handler();
        msgHandler = new Handler();
        initViewPager();
        initRunnable();
    }


    //数据拉取失败的回调
    @Override
    public void netError(int what) {
        Toast.makeText(getActivity(), "网络数据拉取错误+" + what, Toast.LENGTH_SHORT).show();

    }

    //数据拉取成功时的回调
    @Override
    public void netSuccess(int what, Object object) {
        switch (what) {
            case WHAT_ROTATE_PAGE:
                picEntity = ((Rotate) object).getPic();//拉取数据
                urls = picEntity;
                adapter = new RecommPagerAdapter(getActivity(), urls);
                viewPager.setAdapter(adapter);
                this.dot();
                viewPager.addOnPageChangeListener(this);
                isNetDone = true;
                break;
            case WHAT_SONGLIST:
                songList = ((SongListRecomm) object).getContent().getList();
                songListAdapter = new RecommSongListAdapter(getActivity(), songList);
                songListGV.setAdapter(songListAdapter);
                break;
            case WHAT_HOT_SONG:
                hotSong = ((RecommHotSong) object).getContent().get(0).getSong_list();
                hotSongAdapter = new RecommHotSongAdapter(getActivity(), hotSong);
                hotSongLV.setAdapter(hotSongAdapter);
                break;
            case WHAT_NEW_SONG:
                newSong = ((NewSong) object).getPlaze_album_list().getRM().getAlbum_list().getList();
                newSongAdapter = new RecommNewSongAdapter(getActivity(), newSong);
                newSongGV.setAdapter(newSongAdapter);
                break;
        }

    }

    // 设置小圆点方法
    public void dot() {
        for (int i = 0; i < urls.size(); i++) {
            ImageView img = new ImageView(getActivity());
            if (img == null){
                Toast.makeText(getActivity(), "非空", Toast.LENGTH_SHORT).show();
            }else {
                img.setPadding(5, 0, 5, 0);
                LayoutParams lp = new LayoutParams(25, 25);
                if (i == 0) {
                    img.setImageResource(R.mipmap.ktv_recording_tips_on);
                } else {
                    img.setImageResource(R.mipmap.ktv_recording_tips_off);
                }
                linearLayout.addView(img);
            }
        }
        // 设置页面的页数, 对长度取余时让页面从第零个位置开始
        viewPager.setCurrentItem(6 * 40);
    }

    public void initViewPager() {
        viewPager = (ViewPager) getActivity().findViewById(R.id.viewPager);
        viewPager.addOnPageChangeListener(this);
        // 容器(装轮播图小点)
        linearLayout = (LinearLayout) getActivity().findViewById(R.id.viewPicture);

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        currentPage = position;
    }

    @Override
    public void onPageSelected(int position) {
        if(isNetDone){//测试过后需要改动

        for (int i = 0; i < urls.size(); i++) {
            ImageView img = (ImageView) linearLayout.getChildAt(i);
            img.setImageResource(R.mipmap.ktv_recording_tips_off);
        }
        ImageView img = (ImageView) linearLayout.getChildAt(position % urls.size());
        img.setImageResource(R.mipmap.ktv_recording_tips_on);
        }

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * 开启子线程通知viewpager自动播放
     */
    protected void initRunnable() {
        //括号中是线程的名,随便起名
        handlerThread = new HandlerThread("");
        handlerThread.start();
        msgHandler = new Handler(handlerThread.getLooper()) {
            //接收消息
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                backRunning();
                if (isFlag) {
                    msgHandler.sendEmptyMessageDelayed(10, 2000);
                }
            }
        };
    }

    private void backRunning() {
        startHandler.post(new Runnable() {
            @Override
            public void run() {
                viewPager.setCurrentItem(currentPage++);
            }
        });
    }

    // 重新开始
    @Override
    public void onResume() {
        super.onResume();
        isFlag = true;
        msgHandler.sendEmptyMessage(10);
    }

    @Override
    public void onPause() {
        super.onPause();
        isFlag = false;
        msgHandler.removeMessages(10);
    }

}
